<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="赛项名称" prop="dictValue">
            <el-input
               v-model="queryParams.dictValue"
               placeholder="请输入赛项名称"
               clearable
               style="width: 200px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="赛项状态" clearable style="width: 200px">
               <el-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
<!--         <el-col :span="1.5">-->
<!--            <el-button-->
<!--               type="primary"-->
<!--               plain-->
<!--               icon="Plus"-->
<!--               @click="handleAdd"-->
<!--               v-hasPermi="['system:post:add']"-->
<!--            >新增</el-button>-->
<!--         </el-col>-->
<!--         <el-col :span="1.5">-->
<!--            <el-button-->
<!--               type="success"-->
<!--               plain-->
<!--               icon="Edit"-->
<!--               :disabled="single"-->
<!--               @click="handleUpdate"-->
<!--               v-hasPermi="['system:post:edit']"-->
<!--            >修改</el-button>-->
<!--         </el-col>-->
<!--         <el-col :span="1.5">-->
<!--            <el-button-->
<!--               type="danger"-->
<!--               plain-->
<!--               icon="Delete"-->
<!--               :disabled="multiple"-->
<!--               @click="handleDelete"-->
<!--               v-hasPermi="['system:post:remove']"-->
<!--            >删除</el-button>-->
<!--         </el-col>-->
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Upload"
              @click="handleUpload"
              v-hasPermi="['system:post:remove']"
          >批量导入大赛</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:post:export']"
          >导出</el-button>
        </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

     <el-table  v-loading="loading" :data="eventList" row-key="parentid"
               :tree-props="{ children: 'competitionItemVos', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
<!--       <el-table-column  type="selection"  width="50"></el-table-column>-->
       <el-table-column prop="id" label="编号"  align="center"  width="160"/>
       <el-table-column prop="competitionName" label="赛事名称"  align="center"  width="160" :show-overflow-tooltip="true"/>
       <el-table-column prop="itemName" label="赛项名称" align="center" width="160" :show-overflow-tooltip="true"/>
       <el-table-column prop="status" label="状态" width="160" align="center">
         <template #default="scope">
           <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
         </template>
       </el-table-column>
       <el-table-column label="创建时间" align="center" prop="createTime">
         <template #default="scope">
           <span>{{ parseTime(scope.row.createTime,"{y}-{m}-{d}") }}</span>
         </template>
       </el-table-column>
       <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
         <template #default="scope">
           <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:menu:edit']">
             修改
           </el-button>
<!--           <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:menu:add']">-->
<!--             新增-->
<!--           </el-button>-->
           <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                      v-hasPermi="['system:menu:remove']">删除
           </el-button>
         </template>
       </el-table-column>
     </el-table>

      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNo"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />

      <!-- 添加或修改岗位对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="postRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="赛事名称" prop="dictValue" v-show="CompetitionIsShow" >
               <el-input v-model="form.competitionName" placeholder="请输入赛事名称" readonly/>
            </el-form-item>
           <el-form-item label="赛项名称" prop="dictValue"  v-show="itemNameIsShow">
             <el-input v-model="form.itemName" placeholder="请输入赛项名称"  readonly/>
           </el-form-item>
            <el-form-item label="赛项状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
<!--     批量导入赛事对话框-->
     <el-dialog :title="UploadTitle" v-model="openUpload" width="500px" append-to-body>
       <el-upload
           v-model:file-list="filelist"
           ref="eventRef"
           class="upload-demo"
           drag
           multiple
           accept=".xls"
           :limit="limit"
           :on-exceed="handleOnexceed"
           :on-success="handleOnsuccess"
           :http-request="handleHttprequest"
           :auto-upload="false"
       >
         <el-icon class="el-icon--upload"><upload-filled /></el-icon>
         <div class="el-upload__text">
           将文件拖到此处,<em>或点击上传</em>
         </div>
         <template #tip>
           <div class="el-upload__tip">
             请按照模板上传文件
           </div>
         </template>
       </el-upload>
       <template #footer>
         <div class="dialog-footer">
           <el-button type="warning" @click="DownWord">下载模板</el-button>
           <el-button type="primary" @click="submitDow">导 入</el-button>
           <el-button @click="cancelEvent">取 消</el-button>
         </div>
       </template>
     </el-dialog>
   </div>
</template>

<script setup name="Post">
// import { listPost, addPost, delPost, getPost, updatePost } from "@/api/system/post";
import {UploadDoc,updateEvnet,addEvent,delEvent,geteventList,changeEvent,changeItem,delItem} from "@/api/contest/_event"
import {ElMessage, ElMessageBox} from "element-plus";
import { UploadFilled } from '@element-plus/icons-vue'
import {getToken} from "@/utils/_auth";
import SvgIcon from "@/components/SvgIcon/index.vue";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const filelist = ref([])
const eventList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([])
const itemNamess = ref([])
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openUpload=ref(false);
const UploadTitle=ref("")
const disabled = ref(false)
let limit = "1"
const itemNameIsShow = ref(false)
const CompetitionIsShow = ref(false)
const flag = ref(false)
const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    competitionName: undefined,
    itemName: undefined,
    competitionStatus: undefined,
    itemStatus: undefined,
  },
});
const { queryParams, form, rules } = toRefs(data);
/**下载模板*/
function DownWord() {
  proxy.download("/admin/competition/template/download", {}, `template_${new Date().getTime()}.xls`);
}
/** 查询大赛列表 */
function getList() {
  loading.value = true;
  geteventList(queryParams.value).then(response=>{
    // console.log(response.data.result)
    eventList.value = response.data.result
    for(let i=0;i<eventList.value.length;i++){
      eventList.value[i].parentid = eventList.value[i].id
    }
    total.value = response.data.total
  })
  // console.log(tableData.value.competitonlist)
  // eventList.value=tableData.value.competitonlist

  // });
loading.value = false;
}
/**导入大赛对话框*/
function handleUpload(){
  filelist.value=""
  UploadTitle.value="批量导入大赛"
  openUpload.value=true
}
/**超出限制提醒*/
function handleOnexceed(){
  ElMessage.error("只允许上传一张表格")
}
/**上传成功提示*/
function handleOnsuccess(){
  ElMessage.success("上传成功")
}
/**导入文件*/
function handleHttprequest(uploadfile){
  debugger
  let file = uploadfile
  let data = new FormData();
  data.append("file",file)
  console.log(data)
  UploadDoc(data).then(response=>{
    openUpload.value = false
    ElMessage.success("导入成功")
    getList()
  })
}
/**提交文件*/
function submitDow(){
  if(filelist.value.length===0){
    ElMessage.error("请提交文件后上传")
  }else{
    handleHttprequest(filelist.value[0].raw)
  }
}
/**关闭导入对话框按钮*/
function cancelEvent(){
  filelist.value = ""
  openUpload.value = false
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    itemNameIsShow:false
  };
  proxy.resetForm("postRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  names.value =selection.map(item=>item.competitionName)
  itemNamess.value = selection.map(item=>item.itemName)
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  disabled.value = false
  open.value = true;
  title.value = "添加大赛";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  if(row.competitionName!==null&&row.competitionName!==undefined){
    form.value=row
    CompetitionIsShow.value=true
    itemNameIsShow.value=false
    flag.value=true
    title.value="修改赛事"
  }else{
    form.value=row
    CompetitionIsShow.value=false
    itemNameIsShow.value=true
    title.value="修改赛项"
    flag.value=false
  }
  open.value=true
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if(flag.value===true){
        changeEvent(form.value).then(response => {
          proxy.$modal.msgSuccess("赛事修改成功");
          open.value = false;
          getList();
        });
      }else if(flag.value===false){
        changeItem(form.value).then(response => {
          proxy.$modal.msgSuccess("赛项修改成功");
          open.value = false;
          getList();
        });
      }
      }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  const name = row.competitionName || names.value
  const itemNames=row.itemName ||itemNamess.value
  console.log(row.competitionName)
  if(row.competitionName!=null&&row.competitionName!=undefined){
    if(row.competitionItemVos.length!=0){
      proxy.$modal.msgError("该赛事下有赛项无法删除");
    }else{
      proxy.$modal.confirm('是否确认删除"' + name + '"的赛事？').then(function() {
        console.log(id)
        return delEvent(id);
      }).then(() => {
        getList();
        proxy.$modal.msgSuccess("赛事删除成功");
      }).catch(() => {});
    }
  }else{
    proxy.$modal.confirm('是否确认删除"' + itemNames + '"的赛项？').then(function() {
      console.log(id)
      return delItem(id);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("赛项删除成功");
    }).catch(() => {});
  }





  // const id = row.id || ids.value;
  // const name = row.competitionName || names.value
  // const itemNames=row.itemName ||itemNamess.value
  // if(row.competitionItemVos===null){
  //   ElMessage.error("该赛事下有赛项,无法删除")
  // }else{
  //     proxy.$modal.confirm('是否确认删除"' + name + '"的赛事？').then(function() {
  //       return delEvent(id);
  //     }).then(() => {
  //       getList();
  //       proxy.$modal.msgSuccess("删除成功");
  //     }).catch(() => {});
  // }
  // if(row.competitionName===null&&row.competitionName===undefined){
  //   console.log(row)
  //   proxy.$modal.confirm('是否确认删除"' + itemNames + '"的赛项？').then(function() {
  //     return delItem(id);
  //   }).then(() => {
  //     getList();
  //     proxy.$modal.msgSuccess("删除成功");
  //   }).catch(() => {});
  // }
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download("/admin/competition/export", {
    ...queryParams.value,
  }, `event_${new Date().getTime()}.xlsx`);
}
getList();
</script>
<style>
.el-upload__tip{
  text-align: center;
}
</style>